package utils

import (
	"asystem/db"
	"errors"
	"fmt"
	"github.com/xuri/excelize/v2"
	"os"
	"path/filepath"
	"strconv"
	"time"
)

const SHEET = "物料"

func MkdirFilePath(basePath string) (folder string, err error) {
	folderName := time.Now().Format("2006/01/02")
	folderPath := filepath.Join(basePath, folderName)
	err = os.MkdirAll(folderPath, os.ModePerm)
	if err != nil {
		return "", errors.New(fmt.Sprintf("导入失败，创建文件目录出错，错误代码：%v", err))
	}
	return folderPath, nil
}

func OpenFileToSql(filePath string) error {
	file, err := excelize.OpenFile(filePath)
	if err != nil {
		return errors.New(fmt.Sprintf("导入失败，打开文件错误，错误代码：%v", err))
	}
	rows, err := file.GetRows(SHEET)
	if err != nil {
		return errors.New(fmt.Sprintf("导入失败，读取内容错误，错误代码：%v", err))
	}
	for _, v := range rows[1:] {
		// 开始读取数据并写入数据库操作
		mTid, err := strconv.Atoi(v[3])
		if err != nil {
			return errors.New(fmt.Sprintf("导入失败，物料类型 Id 格式错误，错误代码：%v", err))
		}
		model := &db.Model{Mater: &db.Mater{
			Mname:   v[0],
			Brand:   v[1],
			Model:   v[2],
			MTypeId: mTid,
		}}
		if err = db.InsertFileDatToSql(model); err != nil {
			return errors.New(fmt.Sprintf("%v", err))
		}
	}
	return nil
}
